<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\home\controller;

use think\request;
//use cmf\controller\HomeBaseController;
use think\queue\Queue;
use think\cache\driver\Redis;
class IndexController extends BaseController
{ 

	/**
	*
	*首页
	**/
    public function index()
    {
    	//首页数据展示
    	$ageModel = new \app\home\model\AgeStageModel();
    	$subjectModel = new \app\home\model\SubjectModel();
    	$activityModel = new \app\home\model\ActivityModel();
    	$courseModel = new \app\home\model\CourseModel();
    	$coulabelModel = new \app\home\model\CourseLabelModel();

        $couageModel = new \app\home\model\CourseAgeModel();
        $cousubjectModel = new \app\home\model\CourseSubjectModel();
        $memModel = new \app\home\model\MemberModel();
        $accessModel = new \app\home\model\MemberAccessModel();
        $ckModel = new \app\home\model\CourseSkuModel();


        //获得所有年龄段、学科、轮播图、常驻活动、
        $age_list = $ageModel->getAgeAll('id, name');//年龄段列表

        $banner_list = $activityModel->getActivityBannerList();//banner列表
        foreach ($banner_list as $key => $value) {
            $banner_list[$key]['logo'] = json_img_add_url($value['logo']);
        }

        $rukou_list = $activityModel->getActivityRukouList();//常驻入口列表
         foreach ($rukou_list as $key => $value) {
            $rukou_list[$key]['logo'] = json_img_add_url($value['logo']);
        }
        
        
        //存在邀请码+未绑定上级，进行判断处理
        $member_id = $this->member_id;
        $invite_code = $this->request->param('invite_code', '');//海报自带的邀请码

        $member_info = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname, parent, invite');
        if(!empty($invite_code) && empty($member_info['parent']))
        {
            //查找邀请人信息
            $where = [
                ['invite', '=', $invite_code]
            ];
            $pinfo = $memModel->geetMemberWhereReturnInfo($where, 'member_id, open_id, grade');
            //存在邀请人，并且为星级顾问
            if(!empty($pinfo) && ($pinfo['grade'] >= 2) &&($member_id != $pinfo['member_id']))
            {
                //判断邀请人是否为该用户的下级
                //$res = $this->getMemberIfInviteTop($pinfo['member_id']);
                //if(!$res)
                //{
                    //邀请人不是B的下级，增加一条访客信息
                    $add = [
                        'member_id' => $pinfo['member_id'],
                        'access_id' => $member_id
                    ];
                    $accessModel->addAccessRes($add);

                    //绑定访客，通知消息
                    $notice_contro = new NoticeController();
                    $send_data = [
                        'first' => ['value'=>'有新访客访问了您的分享', 'color'=>"#173177"],
                        'keyword1' => ['value'=> $member_info['nickname'], 'color'=>'#173177'],
                        'keyword2' => ['value'=> '商城首页', 'color'=>'#173177'],
                        'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
                        'remark' => ['value'=> '好友购课后您可以获得收益', 'color'=>'#173177'],
                    ];
                    $return_url = WEB_URL."/my_team?type=3";
                   
                    $notice_contro->sendNoticeMessage('fangke', $send_data, $return_url, '', $pinfo['member_id']);
                //}
            }
        }


        //接收年龄段参数,接受课程ID
        $age_id = $this->request->param('age_id', '', 'intval');
        $subject_id = $this->request->param('subject_id', '', 'intval');

        //根据参数，查找对应学科
        if(!empty($age_id)){
            //课程ID集
            $course_count = $couageModel->getCourseAgeIdCount($age_id);
            
            //去查找对应的学科ID集，然后找学科
            $subject_id_count = $cousubjectModel->getCourseSubjectId($course_count);

            //学科列表
            $subject_list = $subjectModel->getWhereSubjectIdList($subject_id_count, 'id, name');


            //存在年龄段 和 学科
            if(!empty($subject_id))
            {
                //找出该课程里，属于对应学科的信息
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $cousubjectModel->getCourseWhereCourseCountsAndSujectId($course_count, $subject_id, 1, $str);
            }else{
                //默认展示排序最前的三个课程
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $couageModel->getCourseWhereAgeId($age_id, 1, $str);
            }

        }else{

            //只是学科查找
            if(!empty($subject_id))
            {
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $cousubjectModel->getCourseWhereSujectId($subject_id, 1, $str);
            }else{
                 //默认展示排序最前的三个课程
                //$str = 'id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'id, title, basic_number, sales_number, tj_logo';
                $course_list = $courseModel->getIndexCourseList($str, 1);
            }

            //学科列表
            $subject_list = $subjectModel->getSubjectAll('id, name');
        }   

        foreach ($course_list as $key => $value) {
            $course_list[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id,label');
            $course_list[$key]['tj_logo'] = json_img_add_url('/upload/'.$value['tj_logo']);

            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list[$key]['original_money'] = $sku_info['original_money'];
            $course_list[$key]['inventory_number'] = $sku_info['inventory_number'];
        }


        //每天第一次登陆，就展示宝宝信息弹框
        $redis = new Redis();
        $str = 'user_one_login_and_if_not_set_baby'.$member_id;
        $today_login = $redis->get($str);

        $one_login = false;
        $baby_info = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, baby_name, baby_birthday, baby_sex');

        if(empty($baby_info['baby_name']) && empty($today_login))
        {
            $one_login = 1;

            //设置redis
            $times = strtotime('23:59:59') - time();
            $redis->set($str, 1, $times);
        }

        $this->assign('one_login', $one_login);
        $this->assign('invite', $member_info['invite']);
        $this->assign('age_id', $age_id);
        $this->assign('subject_id', $subject_id);
        $this->assign('age_list', $age_list);
        $this->assign('subject_list', $subject_list);
        $this->assign('banner_list', $banner_list);
        $this->assign('rukou_list', $rukou_list);
        $this->assign('course_list', $course_list);

        WL(['msg' => 'index-end'], 'sudu');
        return $this->fetch('index/index');
    }



    /**
    *
    *课程 - 查看更多
    **/
    public function getMoreCourseList()
    {
        $age_id = $this->request->param('age_id', '', 'intval');
        $subject_id = $this->request->param('subject_id', '', 'intval');
        $page = $this->request->param('page', 2, 'intval');

        $courseModel = new \app\home\model\CourseModel();
        $coulabelModel = new \app\home\model\CourseLabelModel();
        $couageModel = new \app\home\model\CourseAgeModel();
        $cousubjectModel = new \app\home\model\CourseSubjectModel();
        $memModel = new \app\home\model\MemberModel();
        $ckModel = new \app\home\model\CourseSkuModel();

        $member_info = $memModel->getMemberIdWhereMemberId($this->member_id, 'member_id, nickname, parent, invite');

        //开始查找
        if(!empty($age_id))
        {
            if(!empty($subject_id))
            {   
                //echo 'a';
                $course_count = $couageModel->getCourseAgeIdCount($age_id);
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $cousubjectModel->getCourseWhereCourseCountsAndSujectId($course_count, $subject_id, $page, $str);
            }else{
                //echo 'b';
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $couageModel->getCourseWhereAgeId($age_id, $page, $str);
            }

        }else{
            //只是学科查找
            if(!empty($subject_id))
            {
                //echo 'c';
                //$str = 'c.id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'c.id, title, basic_number, sales_number, tj_logo';
                $course_list = $cousubjectModel->getCourseWhereSujectId($subject_id, $page, $str);
            }else{
                 //默认展示排序最前的三个课程
                //echo 'd';
                //$str = 'id, title, inventory_number, sell_money, original_money, basic_number, sales_number, tj_logo';
                $str = 'id, title, basic_number, sales_number, tj_logo';
                $course_list = $courseModel->getIndexCourseList($str, $page);
            }
        }

        //echo $courseModel->getLastSql();return;
        foreach ($course_list as $key => $value) {
            $course_list[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id,label');
            $course_list[$key]['tj_logo'] = json_img_add_url('/upload/'.$value['tj_logo']);

            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list[$key]['original_money'] = $sku_info['original_money'];
            $course_list[$key]['inventory_number'] = $sku_info['inventory_number'];
        }

        return return_msg(0, 'ok', ['course_list' => $course_list, 'invite' => $member_info['invite']]);
    }



    /**
    *
    *课程搜索-页面展示
    *
    **/
    public function memberSeekList()
    {
        return $this->fetch('index/search');
    }




    /**
    *
    *课程搜索-列表展示
    *
    **/
    public function getSeekCourseList()
    {
        $title = $this->request->param('title', '');
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        if(empty($title))
        {
            return return_msg(2001, '请输入要搜索的内容');
        }

        if($limit >= 50 || $limit <= 0)
        {
            return return_msg(2002, '每页展示内容不能超过50,并且要大于0');
        }
        //开始搜索
        $courseModel = new \app\home\model\CourseModel();
        $memseekModel = new \app\home\model\MemberSeekModel();
        $coulabelModel = new \app\home\model\CourseLabelModel();
        $memberModel = new \app\home\model\MemberModel();
        $ckModel = new \app\home\model\CourseSkuModel();

        //$str = 'id, title, inventory_number, sell_money, original_money, basic_number, sales_number, xt_logo';
        $str = 'id, title, basic_number, sales_number, xt_logo';
        $course_list = $courseModel->getSeekCourseList($title, $str, $page, $limit);

        foreach ($course_list as $key => $value) {
            $course_list[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id,label');
            $course_list[$key]['tj_logo'] = json_img_add_url('/upload/'.$value['xt_logo']);


            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list[$key]['original_money'] = $sku_info['original_money'];
            $course_list[$key]['inventory_number'] = $sku_info['inventory_number'];
        }

        //获取用户搜索记录-最新10条
        $seek_list = $memseekModel->getMemberSeekListNumberTen($this->member_id);

        //是否存在该条搜索
        $info = $memseekModel->checkMemberSeeks($this->member_id, $title);
        if(empty($info))
        {
            //增加用户新的搜索记录
            $add_data = [
                'member_id' => $this->member_id,
                'name' => $title
            ];
            $memseekModel->addMemberSeeks($add_data);
        }

        //用户邀请码
        $meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, invite');
        return return_msg(0, 'ok', ['course_list' => $course_list, 'seek_list' => $seek_list, 'invite' => $meminfo['invite']]);
    }




    /**
    *
    *搜索历史-记录
    *
    **/
    public function memberSeekHistory()
    {
        $memseekModel = new \app\home\model\MemberSeekModel();

        //获取用户搜索记录-最新10条
        $seek_list = $memseekModel->getMemberSeekListNumberTen($this->member_id);

        return return_msg(0, 'ok', $seek_list);
    }




    /**
    *
    *清空搜索历史
    *
    **/
    public function delMemberSeeks()
    {   
        $memseekModel = new \app\home\model\MemberSeekModel();
        $memseekModel->delMemberSeek($this->member_id);
         return return_msg(0, 'ok');
    }



    /**
    *
    *0元学活动、体验课
    *
    **/
    public function zeroMoneyStudyActive()
    {
        $page = $this->request->param('page', 1, 'intval');
        $type = $this->request->param('type', 1, 'intval');//1 = 0元学   2=体验课

        $courseModel = new \app\home\model\CourseModel();
        $coulabelModel = new \app\home\model\CourseLabelModel();
        $memberModel = new \app\home\model\MemberModel();
        $ckModel = new \app\home\model\CourseSkuModel();
        
        //找出所有0元的课程,并且已经上架的
        //$str = 'c.id, c.title, c.inventory_number, c.sell_money, c.original_money, c.basic_number, c.sales_number, c.xt_logo';
        $str = 'c.id, c.title, c.basic_number, c.sales_number, c.xt_logo';
        $course_list =  $courseModel->getzeroMoneyStudyList($page, $str, $type);

        //找出用户邀请码
        $meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, invite');   
        foreach ($course_list as $key => $value) {
            $course_list[$key]['title'] = titleLong($value['title']);
            $course_list[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id, label');
            $course_list[$key]['xt_logo'] = json_img_add_url('/upload/'.$value['xt_logo']);

            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list[$key]['original_money'] = $sku_info['original_money'];
            $course_list[$key]['inventory_number'] = $sku_info['inventory_number'];
        }

        if($this->request->isAjax()){
            return return_msg(0, 'ok', ['page' => $page, 'course_list' => $course_list, 'invite' => $meminfo['invite']]);
        }else{
            $logo = WEB_URL.'/upload/default/20200717/071701qmyx.png?v='.time();
            if($type == 2)
            {
                $logo = WEB_URL.'/upload/default/20200717/071704qmyx.png?v='.time();
            }
 
            $this->assign('invite', $meminfo['invite']);
            $this->assign('type', $type);
            $this->assign('logo', $logo);
            $this->assign('course_list', $course_list);
            return $this->fetch('index/zero_active');
        }
    }


    /**
    *
    *0.01元，升级顾问页面
    *
    **/   
    public function zeroMoneyStudyUpdateGrade()
    {
        $memberModel = new \app\home\model\MemberModel();
        $courseModel = new \app\home\model\CourseModel();
        $coulabelModel = new \app\home\model\CourseLabelModel();
        $actModel = new \app\home\model\ActivityOneModel();
        $orderModel = new \app\home\model\OrdersModel();
        $ckModel = new \app\home\model\CourseSkuModel();

        //找出所有0.01元的课程,并且已经上架的
        //$str = 'id, title, inventory_number, sell_money, original_money, basic_number, sales_number, xt_logo';
        $str = 'id, title, basic_number, sales_number, xt_logo';
        $course_list =  $courseModel->zeroMoneyStudyUpdateGrade($str);

        foreach ($course_list as $key => $value) {
            $course_list[$key]['title'] = titleLong($value['title']);
            $course_list[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id, label');
            $course_list[$key]['xt_logo'] = json_img_add_url('/upload/'.$value['xt_logo']);

            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list[$key]['original_money'] = $sku_info['original_money'];
            $course_list[$key]['inventory_number'] = $sku_info['inventory_number'];
        }


        //再去10个体验课的课程展示
        //$str = 'c.id, c.title, c.inventory_number, c.sell_money, c.original_money, c.basic_number, c.sales_number, c.xt_logo';
         $str = 'c.idid, c.idtitle, c.idbasic_number, c.idsales_number, c.idxt_logo';
        $course_list_two =  $courseModel->getzeroMoneyStudyList(1, $str, 2);
        foreach ($course_list_two as $key => $value) {
            $course_list_two[$key]['title'] = titleLong($value['title']);
            $course_list_two[$key]['label'] = $coulabelModel->getCourseLabelList($value['id'], 'id, label');
            $course_list_two[$key]['xt_logo'] = json_img_add_url('/upload/'.$value['xt_logo']);

            //第三版，规格下单 - 最低价规格的价格
            $sku_info = $ckModel->getCourseSkuLowestPriceInfo($value['id']);
            $course_list_two[$key]['sell_money'] = $sku_info['sell_money'];
            $course_list_two[$key]['original_money'] = $sku_info['original_money'];
            $course_list_two[$key]['inventory_number'] = $sku_info['inventory_number'];
        }
        
        $logo = WEB_URL.'/upload/default/20200717/071703qmyx.png?v='.time();

        $if_click = 0;
        //找到用户邀请码
        $meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, invite, grade');   

        //是否已报名
        $actinfo = $actModel->getMemberActInfo($this->member_id);


        //普通用户 & 未报名
        if($meminfo['grade'] == 1 && empty($actinfo))
        {
            //购买过课程?
            $order_info = $orderModel->getMemberOrderAddtimeAsc($this->member_id, 'order_id, add_time');
            if(!empty($order_info))
            {
                $if_click = 1;
            }else{
                 $if_click = 2;//请先购买课程
            }
        }


        $this->assign('invite', $meminfo['invite']);
        $this->assign('if_click', $if_click);
        $this->assign('logo', $logo);
        $this->assign('course_list', $course_list);
        $this->assign('course_list_two', $course_list_two);

        return $this->fetch('index/update_grade');
    }



    /**
    *
    *立即报名页面
    *
    **/
    public function applyActivity()
    {
        $memberModel = new \app\home\model\MemberModel();
        $actModel = new \app\home\model\ActivityOneModel();
        //找到用户邀请码
        $meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, parent');

        //找到用户是否已报名了
        $actinfo = $actModel->getMemberActInfo($this->member_id);

        $this->assign('parent', $meminfo['parent']);
        $this->assign('actinfo', $actinfo);
        return $this->fetch('index/guanzhu');
    }


    /**
    *
    *报名成功，申请参与活动
    *
    **/
    public function addApplyMemberInfo()
    {
        $member_id = $this->member_id;
        $memberModel = new \app\home\model\MemberModel();
        $actModel = new \app\home\model\ActivityOneModel();

        //找到用户邀请码
        $meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, parent');
        if(empty($meminfo['parent']))
        {
            return return_msg(2001, '您还未绑定邀请人，报名失败');
        }

        $actinfo = $actModel->getMemberActInfo($this->member_id);
        if(empty($actinfo))
        {
            //添加一条报名活动成功的信息
            $actModel->addActivityOne(['member_id' => $member_id]);
        }

        return return_msg(200, 'ok');
    }

}
